package com.lzy.business.controller.statistics;

import com.github.pagehelper.PageInfo;
import com.lzy.business.request.BaseRequest;
import com.lzy.business.request.statistics.DayProfitRequest;
import com.lzy.business.request.statistics.OrderProfitRecordRequest;
import com.lzy.business.request.statistics.OrderProjectRequest;
import com.lzy.business.response.statistics.DayProfitResponse;
import com.lzy.business.response.statistics.OrderProfitRecordResponse;
import com.lzy.business.response.statistics.OrderProjectRecordVoResponse;
import com.lzy.business.response.statistics.TotalProfitResponse;
import com.lzy.framework.component.PageBean;
import com.lzy.framework.core.excel.SimpleExcelExportUtils;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.utils.CollectionUtils;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.WebUtils;
import com.lzy.product.apis.OrderProfitServiceApi;
import com.lzy.product.apis.StatisticsServiceApi;
import com.lzy.product.common.util.EnumUtil;
import com.lzy.product.constants.BusinessType.ProjectType;
import com.lzy.product.constants.profit.ProfitTargetEnum;
import com.lzy.product.dtos.BaseDomain;
import com.lzy.product.dtos.statistics.*;
import com.lzy.web.exception.GenericException;
import com.lzy.web.response.excel.statistics.TotalProfitExportResponse;
import com.lzy.web.response.excel.statistics.dayProfit.OtherProfitExportResponse;
import com.lzy.web.response.excel.statistics.dayProfit.PersonalProfitExportResponse;
import com.lzy.web.response.excel.statistics.project.CarCouponProjectExportResponse;
import com.lzy.web.response.excel.statistics.project.DragonProjectExportResponse;
import com.lzy.web.response.excel.statistics.project.MotorCouponProjectExportResponse;
import com.lzy.web.response.excel.statistics.project.StockRightsProjectExportResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by WIN7 on 2017/12/9.
 */
@Controller
@RequestMapping("admin/statistics")
public class StatisticsController {
    private static final Logger logger = LoggerFactory.getLogger(StatisticsController.class);
    @Autowired
    private StatisticsServiceApi statisticsServiceApi;
    @Autowired
    private OrderProfitServiceApi orderProfitServiceApi;

    /**
     * 个人统计日收益页面
     *
     * @return
     */
    @RequestMapping(value = "statisticsViewPage", method = RequestMethod.GET)
    public String statisticsViewPage(Model model) {
        StatisticsVoDto voDto = statisticsServiceApi.queryStatisticsView();
        model.addAttribute("voDto", voDto);
        return "product/statistics/statistics_view";
    }

    /**
     * 个人统计列表页面
     *
     * @return
     */
    @RequestMapping(value = "totalProfitListPage", method = RequestMethod.GET)
    public String totalProfitListPage() {
        return "product/statistics/total_profit_list";
    }

    /**
     * 个人统计列表   返回json在页面
     */
    @RequestMapping(value = "/json", method = RequestMethod.GET)
    @ResponseBody
    public PageBean totalProfitList(BaseRequest request) {
        Pager pager = new Pager();
        pager.setPageSize(request.getPageSize());
        pager.setPageNum(request.getPageNum());
        PageInfo<TotalProfitVoDto> pageInfo = statisticsServiceApi.queryTotalProfitList(pager, DozerUtils.map(request, BaseDomain.class));
        if (pageInfo != null) {
            return new PageBean(pageInfo.getTotal(), DozerUtils.maps(pageInfo.getList(), TotalProfitResponse.class));
        }
        return null;
    }

    /**
     * 个人统计日收益页面
     *
     * @return
     */
    @RequestMapping(value = "personalProfitListPage/{userId}", method = RequestMethod.GET)
    public String personalProfitListPage(Model model, @PathVariable("userId") Long userId) {
        PersonalProfitVoDto voDto = statisticsServiceApi.queryPersonalProfit(userId);
        model.addAttribute("voDto", voDto);
        return "product/statistics/personal_profit_list";
    }

    /**
     * 个人统计日收益列表   返回json在页面
     */
    @RequestMapping(value = "/personalProfit/json", method = RequestMethod.GET)
    @ResponseBody
    public DayProfitResponse personalProfitList(DayProfitRequest request) {
        DayProfitParamDto paramDto = DozerUtils.map(request, DayProfitParamDto.class);
        DayProfitResponse response = new DayProfitResponse();
        //查询分利
        String queryProfit = statisticsServiceApi.getQueryProfit(paramDto);
        response.setQueryProfit(queryProfit);

        //日收益列表
        Pager pager = new Pager();
        pager.setPageSize(request.getPageSize());
        pager.setPageNum(request.getPageNum());
        PageInfo<DayProfitVoDto> pageInfo = statisticsServiceApi.queryDayProfitList(pager, paramDto);
        if (pageInfo != null) {
            PageBean<DayProfitVoDto> pageBean = new PageBean(pageInfo.getTotal(), pageInfo.getList());
            response.setDtoPageBean(pageBean);
            return response;
        }

        return null;
    }

    /**
     * 收益来源个人订单收益页面
     *
     * @return
     */
    @RequestMapping(value = "personalRecordListPage", method = RequestMethod.GET)
    public String personalRecordListPage(Model model, Long userId, String date) {
        model.addAttribute("userId", userId);
        model.addAttribute("date", date);
        return "product/statistics/personal_record_list";
    }

    /**
     * 收益来源其他收益页面
     *
     * @return
     */
    @RequestMapping(value = "otherRecordListPage", method = RequestMethod.GET)
    public String otherRecordListPage(Model model, Long userId, String date) {
        model.addAttribute("userId", userId);
        model.addAttribute("date", date);
        return "product/statistics/other_record_list";
    }

    /**
     * 收益来源列表   返回json在页面
     */
    @RequestMapping(value = "/profitRecord/json", method = RequestMethod.GET)
    @ResponseBody
    public PageBean profitRecordList(OrderProfitRecordRequest request) {
        Pager pager = new Pager();
        pager.setPageSize(request.getPageSize());
        pager.setPageNum(request.getPageNum());
        PageInfo<OrderProfitRecordDto> pageInfo = orderProfitServiceApi.queryRecordList(pager, DozerUtils.map(request, OrderProfitRecordDto.class));
        if (pageInfo != null) {
            return new PageBean(pageInfo.getTotal(), DozerUtils.maps(pageInfo.getList(), OrderProfitRecordResponse.class));
        }
        return null;
    }

    /**
     * 综合统计页面
     * type 产品包含项类型(1-龙珠 2-股权 3-房车券 4-汽摩券)
     *
     * @return
     */
    @RequestMapping(value = "projectRecordListPage/{type}", method = RequestMethod.GET)
    public String projectRecordListPage(Model model, @PathVariable("type") Integer type) {
        List<ProjectType> projectTypeList = EnumUtil.valueOfList(ProjectType.class);
        Integer totalProject = statisticsServiceApi.queryTotalProject(type);
        model.addAttribute("projectTypeList", projectTypeList);
        model.addAttribute("totalProject", totalProject);
        model.addAttribute("projectType", type);
        model.addAttribute("projectName", EnumUtil.valueOf(ProjectType.class, type).getDesc());
        return "product/statistics/project_list";
    }

    /**
     * 综合统计列表   返回json在页面
     */
    @RequestMapping(value = "/projectRecord/json", method = RequestMethod.GET)
    @ResponseBody
    public OrderProjectRecordVoResponse projectRecordList(OrderProjectRequest request) {
        OrderProjectParamDto paramDto = DozerUtils.map(request, OrderProjectParamDto.class);
        OrderProjectRecordVoResponse response = new OrderProjectRecordVoResponse();
        //产品包含项类型名称
        response.setProjectName(EnumUtil.valueOf(ProjectType.class, paramDto.getProjectType()).getDesc());
        //查询产生的产品包含项数额
        response.setQueryCount(statisticsServiceApi.getQueryProject(paramDto));
        //总计产生的产品包含项数额
        Integer totalProject = statisticsServiceApi.queryTotalProject(paramDto.getProjectType());
        response.setTotalCount(totalProject);

        //分页数据
        Pager pager = new Pager();
        pager.setPageSize(request.getPageSize());
        pager.setPageNum(request.getPageNum());
        PageInfo<OrderProjectRecordVoDto> pageInfo = statisticsServiceApi.queryDayProjectList(pager, paramDto);
        if (pageInfo != null) {
            PageBean<OrderProjectRecordVoDto> pageBean = new PageBean(pageInfo.getTotal(), pageInfo.getList());
            response.setDtoPageBean(pageBean);
            return response;
        }
        return null;
    }

    /**
     * 导出个人统计列表
     *
     * @param request
     * @param response
     * @param listRequest
     */
    @RequestMapping(value = "/exportTotalProfit")
    public void exportTotalProfit(HttpServletRequest request, HttpServletResponse response, BaseRequest listRequest) {
        try {
            Pager pager = new Pager();
            pager.setPageSize(10000);
            BaseDomain paramDto = DozerUtils.map(listRequest, BaseDomain.class);
            PageInfo<TotalProfitVoDto> pageInfo = statisticsServiceApi.queryTotalProfitList(pager, paramDto);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            List<TotalProfitVoDto> list = pageInfo.getList();
            if (CollectionUtils.isNotEmpty(list)) {
                if (list.size() > 10000)
                    throw new GenericException("导出数据量过大,请重新输入检索条件,分批导出！");
                LinkedList<TotalProfitExportResponse> voList = new LinkedList<>();
                TotalProfitExportResponse vo;
                for (TotalProfitVoDto voDto : list) {
                    vo = new TotalProfitExportResponse();
                    BeanUtils.copyProperties(voDto, vo);
                    voList.add(vo);
                }

                SimpleExcelExportUtils excelExportService = new SimpleExcelExportUtils();
                HSSFWorkbook wb = new HSSFWorkbook();
                if (voList != null && voList.size() > 0) {
                    wb = excelExportService.generateExcel(voList);
                }
                String fileName = "个人统计" + sdf.format(new Date()) + ".xls";
                // 设定输出文件头
                WebUtils.prepareDownloadFile(fileName, "application/msexcel", request, response);
                OutputStream out = response.getOutputStream();
                wb.write(out);
                out.close();
            } else {
                logger.error("没有可执行数据：个人统计数据导出EXCEL失败！");
            }
        } catch (Exception e) {
            logger.error("个人统计数据导出EXCEL失败！", e);
            throw new GenericException("个人统计数据导出EXCEL失败");
        }
    }

    /**
     * 导出来源收益统计列表
     *
     * @param request
     * @param response
     * @param listRequest
     */
    @RequestMapping(value = "/exportProfitRecord")
    public void exportProfitRecord(HttpServletRequest request, HttpServletResponse response, OrderProfitRecordRequest listRequest) {
        try {
            Pager pager = new Pager();
            pager.setPageSize(10000);
            PageInfo<OrderProfitRecordDto> pageInfo = orderProfitServiceApi.queryRecordList(pager, DozerUtils.map(request, OrderProfitRecordDto.class));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            List<OrderProfitRecordDto> list = pageInfo.getList();
            if (CollectionUtils.isNotEmpty(list)) {
                if (list.size() > 10000)
                    throw new GenericException("导出数据量过大,请重新输入检索条件,分批导出！");

                LinkedList voList = null;
                String res;
                if (ProfitTargetEnum.ONE_LEVEL.getCode().equals(listRequest.getLevel())) {  //个人订单收益记录
                    voList = new LinkedList<PersonalProfitExportResponse>();
                    PersonalProfitExportResponse vo;
                    for (OrderProfitRecordDto voDto : list) {
                        vo = new PersonalProfitExportResponse();
                        BeanUtils.copyProperties(voDto, vo);
                        voList.add(vo);
                    }
                    res = "个人订单收益列表";
                } else { //其他收益来源记录
                    voList = new LinkedList<OtherProfitExportResponse>();
                    OtherProfitExportResponse vo;
                    for (OrderProfitRecordDto voDto : list) {
                        vo = new OtherProfitExportResponse();
                        BeanUtils.copyProperties(voDto, vo);
                        voList.add(vo);
                    }
                    res = "其他来源收益列表";
                }
                SimpleExcelExportUtils excelExportService = new SimpleExcelExportUtils();
                HSSFWorkbook wb = new HSSFWorkbook();
                if (voList != null && voList.size() > 0) {
                    wb = excelExportService.generateExcel(voList);
                }
                String fileName = res + sdf.format(new Date()) + ".xls";
                // 设定输出文件头
                WebUtils.prepareDownloadFile(fileName, "application/msexcel", request, response);
                OutputStream out = response.getOutputStream();
                wb.write(out);
                out.close();
            } else {
                logger.error("没有可执行数据：来源收益数据导出EXCEL失败！");
            }
        } catch (Exception e) {
            logger.error("来源收益数据导出EXCEL失败！", e);
            throw new GenericException("来源收益数据导出EXCEL失败");
        }
    }

    /**
     * 导出综合统计列表
     *
     * @param request
     * @param response
     * @param listRequest
     */
    @RequestMapping(value = "/exportProjectRecord")
    public void exportProjectRecord(HttpServletRequest request, HttpServletResponse response, OrderProjectRequest listRequest) {
        try {
            Pager pager = new Pager();
            pager.setPageSize(10000);
            OrderProjectParamDto paramDto = DozerUtils.map(listRequest, OrderProjectParamDto.class);
            PageInfo<OrderProjectRecordVoDto> pageInfo = statisticsServiceApi.queryDayProjectList(pager, paramDto);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            List<OrderProjectRecordVoDto> list = pageInfo.getList();
            if (CollectionUtils.isNotEmpty(list)) {
                if (list.size() > 10000)
                    throw new GenericException("导出数据量过大,请重新输入检索条件,分批导出！");
                LinkedList voList = new LinkedList<>();
                String res = "";
                if (ProjectType.DRAGON.getCode().equals(listRequest.getProjectType())) {  //龙珠
                    DragonProjectExportResponse vo;
                    for (OrderProjectRecordVoDto voDto : list) {
                        vo = new DragonProjectExportResponse();
                        BeanUtils.copyProperties(voDto, vo);
                        voList.add(vo);
                    }
                    res = "产生龙珠记录";
                } else if (ProjectType.STOCK_RIGHTS.getCode().equals(listRequest.getProjectType())) { //股权
                    StockRightsProjectExportResponse vo;
                    for (OrderProjectRecordVoDto voDto : list) {
                        vo = new StockRightsProjectExportResponse();
                        BeanUtils.copyProperties(voDto, vo);
                        voList.add(vo);
                    }
                    res = "产生股权记录";
                } else if (ProjectType.CAR_COUPON.getCode().equals(listRequest.getProjectType())) {  //房车券
                    CarCouponProjectExportResponse vo;
                    for (OrderProjectRecordVoDto voDto : list) {
                        vo = new CarCouponProjectExportResponse();
                        BeanUtils.copyProperties(voDto, vo);
                        voList.add(vo);
                    }
                    res = "产生房车券记录";
                } else if (ProjectType.MOTOR_COUPON.getCode().equals(listRequest.getProjectType())) {  //汽摩券
                    MotorCouponProjectExportResponse vo;
                    for (OrderProjectRecordVoDto voDto : list) {
                        vo = new MotorCouponProjectExportResponse();
                        BeanUtils.copyProperties(voDto, vo);
                        voList.add(vo);
                    }
                    res = "产生汽摩券记录";
                }
                SimpleExcelExportUtils excelExportService = new SimpleExcelExportUtils();
                HSSFWorkbook wb = new HSSFWorkbook();
                if (voList != null && voList.size() > 0) {
                    wb = excelExportService.generateExcel(voList);
                }
                String fileName = "综合统计" + res + sdf.format(new Date()) + ".xls";
                // 设定输出文件头
                WebUtils.prepareDownloadFile(fileName, "application/msexcel", request, response);
                OutputStream out = response.getOutputStream();
                wb.write(out);
                out.close();
            } else {
                logger.error("没有可执行数据：综合统计数据导出EXCEL失败！");
            }
        } catch (Exception e) {
            logger.error("综合统计数据导出EXCEL失败！", e);
            throw new GenericException("综合统计数据导出EXCEL失败");
        }
    }
}
